<?php

namespace app\common\service\driver;

use app\common\constant\driving\CommonConstant;
use app\common\constant\driving\DriverMoneyLogConstant;
use app\common\model\driving\DriverWithdrawal;
use think\Db;
use think\Exception;

/**
 * 司机提现服务类
 **/
class DriverWithdrawalService
{

    /**
     * 提现
     *
     * @param string $amount 提现金额
     * @param string $paytype 支付类型
     * @param string $identity 支付宝登录号
     * @param string $name 支付宝账号姓名
     * @param mixed $user 用户信息
     * @return bool
     */
    public static function create($amount, $paytype, $identity = '', $name = '', $user)
    {
        $epay = get_addon_info('epay');
        if (empty($epay) || !$epay['state']) {
            except("请先在后台安装并配置微信支付宝整合插件");
        }
        if ($paytype == CommonConstant::PAYTYPE_WECHAT && !$user['openid']) {
            except('微信未授权不能提现');
        }
        // TODO 20240711
        if ($paytype == CommonConstant::PAYTYPE_WECHAT) {
            except('微信提现暂未开通');
        }
        if ($amount > $user['money']) {
            except('可提现余额不足');
        }

        $order_no = '2' . get_order_sn($user['id']);
        $data = [
            'user_id' => $user['id'],
            'order_no' => $order_no,
            'amount' => $amount,
            'paytype' => $paytype,
            'openid' => $user['openid'] ? $user['openid'] : '',
            'identity' => $identity ? $identity : '',
            'name' => $name ? $name : '',
            'status' => CommonConstant::W_STATUS_CREATED,
        ];
        Db::startTrans();
        try {
            $log_data = [
                'driver_id' => $user['id'],
                'type' => DriverMoneyLogConstant::TYPE_5,
                'change_type' => DriverMoneyLogConstant::CHANGE_TYPE_2,
                'money' => $amount,
                'memo' => $order_no,
            ];
            DriverService::money($log_data, $user['id'], $user, 'money');
            DriverWithdrawal::create($data);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            except($e->getMessage());
        }

        $money = config('site.withdrawal_money_audit');
        $is_withdrawal = $amount <= $money ? true : false;
        if ($is_withdrawal) {
            $transfer = \addons\epay\library\Service::transfer($paytype, $data);
            $result = self::order_settle($paytype, $order_no, $transfer);
            if (!$result['code']) {
                except($result['msg']);
            }
        }
        return true;
    }

    /**
     * 提现业务逻辑处理 2
     **/
    public static function order_settle($paytype, $order_no, $transfer)
    {
        $order = DriverWithdrawal::where(['order_no' => $order_no])
            ->field('id,user_id,amount,status')
            ->find();
        if (!$order) {
            return V(0, '订单不存在');
        }
        if ($order['status'] != CommonConstant::W_STATUS_CREATED) {
            return V(0, '非申请中状态无法提现');
        }

        $status = CommonConstant::W_STATUS_REJECTED;
        if ($paytype == 'wechat') {
            if (isset($transfer['out_batch_no'])) {
                $status = CommonConstant::W_STATUS_SUCCESSED;
                $data = [
                    'order_no' => $transfer['out_batch_no'],
                    'pay_fund_order_id' => $transfer['batch_id'],
                    'transfertime' => $transfer['create_time'],
                ];
            } else {
                $data['audit_desc'] = '【微信提现】code:' . $transfer['code'] . ',' . $transfer['message'];
            }
        }
        if ($paytype == 'alipay') {
            if ($transfer['code'] == 10000 && $transfer['status'] == 'SUCCESS') {
                $status = CommonConstant::W_STATUS_SUCCESSED;
                $data = [
                    'order_no' => $transfer['out_biz_no'],
                    'transaction_id' => $transfer['pay_fund_order_id'],
                    'transfertime' => $transfer['trans_date'],
                ];
            } else {
                $data['audit_desc'] = '【支付宝提现】code:' . $transfer['code'] . ',' . $transfer['msg'];
            }
        }
        $data['status'] = $status;

        Db::startTrans();
        try {
            if ($status == CommonConstant::W_STATUS_REJECTED) {
                $log_data = [
                    'driver_id' => $order['user_id'],
                    'type' => DriverMoneyLogConstant::TYPE_6,
                    'change_type' => DriverMoneyLogConstant::CHANGE_TYPE_1,
                    'money' => $order['amount'],
                    'memo' => $order_no,
                ];
                DriverService::money($log_data, $order['user_id'], [], 'money');
            }
            $order->save($data);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return V(0, $e->getMessage());
        }
        return V(1, '操作成功');
    }

}
